const express = require('express');
const router = express.Router();
const PrescriptionModel = require('../db/PrescriptionModel');

/**
 * 处方模版
 * crud
 */

router.get('/save', (req, res) => {
    if (req.query.name == '' || req.query.department == '') {
        return res.json({
            code: 201,
            mes: '参数错误。'
        });
    }
    const temp = new PrescriptionModel(req.query);
    temp.save().then(() => {
        return res.json({
            code: 200,
            mes: '模版增加成功。'
        });
    }).catch(() => {
        return res.json({
            code: 202,
            mes: '模版增加失败。'
        });
    })
});

router.get('/remove', (req, res) => {
    const id = req.query.id;
    PrescriptionModel.remove({ _id: id }).then(docs => {
        return res.json({
            code: 200,
            mes: '删除成功。',
            data: docs
        });
    }).catch(() => {
        return res.json({
            code: 202,
            mes: '删除失败。'
        });
    })
});

router.post('/update', (req, res) => {
    const id = req.body.id;
    const temp = req.body;
    if (id == '') {
        return res.json({
            code: 201,
            mes: '参数错误。'
        });
    }
    PrescriptionModel.update({ _id: id }, {
        $set: temp
    }).then(docs => {
        return res.json({
            code: 200,
            mes: '修改成功。',
            data: docs
        });
    }).catch(() => {
        return res.json({
            code: 202,
            mes: '修改失败。'
        });
    })
});

router.get('/find', (req, res) => {
    PrescriptionModel.find().then(docs => {
        return res.json({
            code: 200,
            mes: '查询成功。',
            data: docs
        });
    }).catch(() => {
        return res.json({
            code: 201,
            mes: '查询失败。'
        });
    })
});

router.get('/findone', (req, res) => {
    const id = req.query.id;
    PrescriptionModel.findOne({ _id: id }).then(docs => {
        return res.json({
            code: 200,
            mes: '查询成功。',
            data: docs
        });
    }).catch(() => {
        return res.json({
            code: 201,
            mes: '查询失败。'
        });
    })
});

module.exports = router;
